import Popup from "@/components/com/Popup"
import { ProjectService } from "@/service/projects-api"
import { setCurrPath } from "@/store/tabs"
import { ComUtils } from "@/utils/Com"
import { MessageBox } from "@/utils/messagebox"
import { useNavigate } from "@solidjs/router"
import { createSignal, For, Match, onMount, Show, Switch } from "solid-js"
import { TextEditorConfig } from "../config/text-editor"
import Templat from "../com/Templat"
import { BrowserUtils } from "@/utils/browser"
import { StrUtils } from "@/utils/str"
import { Backups } from "@/utils/backups"
import MyButton from "../com/MyButton"
import '@/assets/css/st-project.css'

const refreshtIcon = ComUtils.getResourceUrl('/icons/refresh.svg')
const delIcon = ComUtils.getResourceUrl('/icons/delete.svg')
const editIcon = ComUtils.getResourceUrl('/icons/edit.svg')
const newIcon = ComUtils.getResourceUrl('/icons/new.svg')
const disabledIcon = ComUtils.getResourceUrl('/icons/disabled.svg')
const enabledIcon = ComUtils.getResourceUrl('/icons/enabled.svg')
const htmlIcon = ComUtils.getResourceUrl('/icons/html.svg')
const downloadIcon = ComUtils.getResourceUrl('/icons/ic-download.svg')
const importIcon = ComUtils.getResourceUrl('/icons/import.svg')
const runIcon = ComUtils.getResourceUrl('/icons/run.svg')
const loadingIcon = ComUtils.getResourceUrl('/icons/loading-g.svg')
const errorIcon = ComUtils.getResourceUrl('/icons/error.svg')
const codeIcon = ComUtils.getResourceUrl('/icons/code.svg')
const sortIcon = ComUtils.getResourceUrl('/icons/list-sort.svg')

const Fields = ['name', 'type', 'programmingType', 'author', 'size', 'error', 'version', 'enabled', 'installTime', 'updateTime', '']

const RunAts = ['document_start', 'document_end', 'document_idle']
const ProjectTypes: ScriptType[] = ['content', 'window', 'sidePanel', 'editorPlugin']
const programmingTypes: ProjectItemProgrammingType[] = ['blockly', 'both', 'text']
export default function () {
    const [projects, setProjects] = createSignal<ProjectItem[]>([]);
    const [originProjects, setOriginProjects] = createSignal<ProjectItem[]>([]);
    const [popup, setPopup] = createSignal(false)
    const [templatPopup, setTemplatPopup] = createSignal(false)
    const [deletePopup, setDeletePopup] = createSignal(false)
    const [currentItem, setCurrentItem] = createSignal<ProjectItem>()
    const [isImporting, setIsImporting] = createSignal(false)
    const [loading, setLoading] = createSignal(false)

    const [itemLoading, setItemLoading] = createSignal({
        id: '',
        loading: false
    })

    const [searchWords, setSearchWords] = createSignal('');
    const [filters, setFilters] = createSignal({
        type: '',
        programmingType: ''
    })
    const [sort, setSort] = createSignal({
        key: '',
        order: -1
    })

    const [form, setForm] = createSignal<ProjectItem>({
        id: '',
        name: "untitled",
        type: 'content',
        programmingType: 'blockly',
        description: "",
        matches: [],
        exclude: [],
        include: [],
        code: TextEditorConfig.getEmptyTemplate(),
        installTime: Date.now(),
        author: "script dog",
        version: "1.0.0",
        enabled: true,
        source: "",
        runAt: 'document_idle',
        useDog: true,
        templates: {},
        requires: [],
        resources: []
    })

    const [windowInfo, setWindowInfo] = createSignal<ProjectItemWindow>({
        icon: '',
        left: undefined,
        top: undefined,
        width: undefined,
        height: undefined
    })

    const [installUrl, setInstallUrl] = createSignal('')

    const navigate = useNavigate()

    const setFormValue = (k: string, val: any) => {
        const obj = { ...form() }
        Reflect.set(obj, k, val)
        setForm(obj)
    }

    const setWindowFormValue = (k: string, val: any) => {
        const obj = { ...windowInfo() }
        Reflect.set(obj, k, val)
        setWindowInfo(obj)
    }

    const loadData = async (kw = '') => {
        setSearchWords(kw)
        const data = await ProjectService.list(searchWords());
        setProjects(data);
        setOriginProjects(data);
        filterData()
    }

    const closePopup = (cancel?: boolean) => {
        setForm({
            id: '',
            name: "untitled",
            type: 'content',
            programmingType: 'blockly',
            description: "",
            matches: [],
            exclude: [],
            include: [],
            code: TextEditorConfig.getEmptyTemplate(),
            source: "",
            installTime: Date.now(),
            author: "script dog",
            version: "1.0.0",
            enabled: true,
            runAt: 'document_idle',
            showRunLogo: true,
            useDog: true,
            useGM: false,
            templates: {},
            requires: [],
            resources: [],
        })
        setIsImporting(false)
        setPopup(false)
        if (installUrl() && cancel) {
            window.close()
        } else if (installUrl() && !cancel) {
            location.href = location.href.split('?')[0]
        }
    }

    const newPopup = () => {
        setPopup(true)
    }

    const editPopup = (item: ProjectItem) => {
        setForm({ ...item })
        setPopup(true)
        if (item.window) {
            setWindowInfo(item.window)
        }
    }

    const deleteData = async () => {
        const item = currentItem()
        if (!item) {
            return
        }
        const ar = projects().filter(i => i.id !== item.id)
        setProjects(ar)
        await ProjectService.remove(item.id)
        setDeletePopup(false)
    }

    const goEditor = (item: ProjectItem) => {
        setCurrPath('/editor')
        navigate(`/editor?id=${item.id}`)
    }

    const showDelete = (item: ProjectItem) => {
        setCurrentItem(item)
        setDeletePopup(true)
    }

    const getValue = (item: ProjectItem, k: string) => {
        return Reflect.get(item, k)
    }

    const getEnabledIcon = (item: ProjectItem) => {
        return item.enabled ? enabledIcon : disabledIcon
    }

    const saveData = async () => {
        const data = { ...form() }
        const ar = [...projects()]
        const index = projects().findIndex(i => i.id === data.id)
        if (index > -1) {
            data.updateTime = Date.now()
            ar[index] = data
        } else {
            data.id = ProjectService.getId()
            ar.push(data)
        }
        if (!/^\d+[\.\d]+\.\d+$/.test(data.version)) {
            MessageBox.error(ComUtils.tr('version_format_error'))
            return
        }

        if (data.type === 'window') {
            data.window = windowInfo()
        } else {
            data.window = undefined
        }
        data.error = undefined
        const encoder = new TextEncoder()
        data.size = encoder.encode(data.code + data.source).length
        setLoading(true)
        try {
            setProjects(ar)
            await ProjectService.save(data);
            await loadData()
            Backups.autoBackup()
            closePopup()
            MessageBox.success(ComUtils.tr('save_success'))

        } catch (error) {
            console.log(error)
            MessageBox.error(ComUtils.tr('save_fail'))
        }
        setLoading(false)
    }

    const saveTemplate = async (item: ProjectItem) => {
        const data = { ...item }
        setForm(data)
        const ar = [...projects()]
        const index = projects().findIndex(i => i.id === data.id)
        if (index > -1) {
            ar[index] = data
        }

        await ProjectService.save(data);
        setProjects(ar);
        Backups.autoBackup();

        setItemLoading({
            id: '',
            loading: false
        })
    }

    const showHtml = (item: ProjectItem) => {
        setForm({ ...item })
        setTemplatPopup(true)
    }

    const getEditPopupTitle = () => {
        if (isImporting()) {
            return ComUtils.tr('import_project')
        }
        return form().id.trim() === '' ? ComUtils.tr('new_project') : ComUtils.tr('edit_project')
    }

    const downloadItem = (item: ProjectItem) => {
        const blob = new Blob([JSON.stringify(item)], { type: 'text/json' });
        const url = URL.createObjectURL(blob);
        ComUtils.downloadFile(url, `${item.name}.json`);
    }

    const importGM = async (txt: string) => {
        const meta = StrUtils.parseGM_Metadata(txt)
        const data: ProjectItem = {
            id: ProjectService.getId(),
            name: meta.name,
            type: 'content',
            programmingType: 'text',
            matches: meta.match?.split(',') || [],
            exclude: meta.exclude?.split(',') || [],
            include: meta.include?.split(',') || [],
            description: meta.description,
            code: txt,
            installTime: Date.now(),
            author: meta.author || 'other',
            version: meta.version,
            enabled: true,
            useDog: true,
            external: true,
            runAt: (meta['run-at'] || 'document_idle').replace('-', '_') as ScriptRunAt,
            templates: {},
            source: "",
            requires: meta.require?.split(',') || [],
            resources: meta.resource?.split(',') || [],
        }
        console.log(meta)
        setIsImporting(true)
        editPopup(data)
    }

    const importProject = async () => {
        const txt = await BrowserUtils.openFile<string>(true).catch(() => '')
        if (!txt) {
            MessageBox.error(ComUtils.tr('import_fail'))
            setLoading(false)
            return
        }
        try {
            const obj = JSON.parse(txt)
            obj.id = ProjectService.getId()
            setIsImporting(true)
            editPopup(obj)
        } catch (error) {
            importGM(txt).catch((e) => {
                console.log(e)
                MessageBox.error(ComUtils.tr('import_fail'))
            })
        }
    }

    const installScript = async (url: string) => {
        setLoading(true)
        const res = await fetch(url).catch(() => undefined)
        if (!res) {
            MessageBox.error(ComUtils.tr('import_fail'))
            setLoading(false)
            return
        }
        const txt = await res.text()
        try {

            const obj = JSON.parse(txt)
            obj.id = ProjectService.getId()
            obj.external = true
            setIsImporting(true)
            editPopup(obj)
        } catch (error) {
            importGM(txt).catch((e) => {
                console.log(e)
                MessageBox.error(ComUtils.tr('import_fail'))
            })
        }
        setLoading(false)
    }

    const runScript = (item: ProjectItem) => {
        if (item.type === 'content') {
            return;
        }
        ComUtils.callChromeMethod('runScript', { id: item.id, sw: screen.width, sh: screen.height }).then(() => {
            if (item.type === 'sidePanel') {
                ComUtils.callChromeMethod('openSidePanel', undefined)
            }
            MessageBox.success(ComUtils.tr('run_success'))
        }).catch(() => {
            MessageBox.error(ComUtils.tr('run_fail'))
        })
    }

    const refreshProject = () => {
        setLoading(true)
        ComUtils.callChromeMethod('updateScripts', {}).then(() => {
            loadData()
            MessageBox.success(ComUtils.tr('refresh_success'))
        }).catch(() => {
            MessageBox.error(ComUtils.tr('refresh_fail'))
        }).finally(() => {
            setLoading(false)
        })
    }

    const toggleEnabled = async (item: ProjectItem) => {
        item.enabled = !item.enabled
        item.error = undefined
        setItemLoading({
            id: item.id,
            loading: true
        })
        await saveTemplate(item);
        setItemLoading({
            id: item.id,
            loading: true
        })
        await ComUtils.callChromeMethod('updateScript', { id: item.id });
        setItemLoading({
            id: item.id,
            loading: false
        })
        MessageBox.success(ComUtils.tr('refresh_success'))
    }

    const sortList = (field: string) => {
        const s = { ...sort() };
        s.key = field;
        if (s.order < 1) {
            s.order += 1;
        } else {
            s.order = -1;
        }
        setSort(s);

        filterData()
    }

    const filterChange = (key: string, val: string) => {
        const f = { ...filters() };
        Reflect.set(f, key, val);
        setFilters(f);
        filterData()
    }

    const filterData = () => {
        //排序
        const ar = originProjects().sort((a, b) => {
            const av = Reflect.get(a, sort().key) || 0;
            const bv = Reflect.get(b, sort().key) || 0;
            if (sort().order == 0) {
                return av - bv;
            } else if (sort().order == 1) {
                return bv - av;
            } else {
                return b.installTime - a.installTime
            }
        })
        //过滤

        const temp = ar.filter(a => {
            if (filters().type === '' && filters().programmingType === '') {
                return true
            } else if (filters().type !== '' && filters().programmingType === '') {
                return a.type === filters().type
            } else if (filters().type === '' && filters().programmingType !== '') {
                return a.programmingType === filters().programmingType
            }
            return a.type === filters().type && a.programmingType === filters().programmingType
        });
        setProjects([...temp]);
    }

    const copyErr = (err?: string) => {
        if (!err) {
            return
        }
        navigator.clipboard.writeText(err);
        MessageBox.success(ComUtils.tr('copied_text'));
    }

    onMount(() => {
        const query = new URLSearchParams(window.location.search)
        const url = query.get('installUrl')
        if (url) {
            setInstallUrl(decodeURIComponent(url))
            installScript(installUrl())
        }
        loadData()
    })
    const loadingBlock = <div class=" fixed left-0 top-0 z-[9999] backdrop:blur bg-[rgba(0,0,0,0.4)] w-full h-full flex items-center justify-center" style={{ 'display': loading() ? 'flex' : 'none' }}>
        <img class="w-16 h-16" src={loadingIcon} alt="loading" />
    </div>
    return <div class="px-5 pb-5">
        {loadingBlock}
        <div class="sticky top-0 z-20 bg-[#181818] flex justify-between items-center gap-3 py-4">
            <div class="flex items-center gap-2">
                <input value={searchWords()} onchange={e => loadData(e.target.value.trim())} type="text" class="bg-[#0a0a0a] text-sm rounded-md" placeholder={ComUtils.tr('search_scripts_input')} />
                <select class="w-full" value={filters().type} onchange={(e) => filterChange('type', e.target.value as any)}>
                    <option value="">
                        {ComUtils.tr('project_type_filter_all')}
                    </option>
                    <For each={ProjectTypes}>
                        {
                            val => <option value={val}>
                                {ComUtils.tr('project_type_' + val)}
                            </option>
                        }
                    </For>
                </select>
                <select class="w-full" value={filters().programmingType} onchange={(e) => filterChange('programmingType', e.target.value as any)}>
                    <option value="">
                        {ComUtils.tr('project_programming_filter_all')}
                    </option>
                    <For each={programmingTypes}>
                        {
                            val => <option value={val}>
                                {ComUtils.tr('programming_type_' + val)}
                            </option>
                        }
                    </For>
                </select>
            </div>
            <div class="flex gap-2 items-center">
                <button title={ComUtils.tr('refresh') + ' ' + ComUtils.tr('project_type_content')} onclick={refreshProject}>
                    <img class='w-6 h-6' src={refreshtIcon} alt="refreshtIcon" />
                </button>
                <button title={ComUtils.tr('import')} onclick={importProject}>
                    <img class='w-6 h-6' src={importIcon} alt="importIcon" />
                </button>
                <button title={ComUtils.tr('new_project')} onclick={newPopup}>
                    <img class='w-6 h-6' src={newIcon} alt="newIcon" />
                </button>
            </div>
        </div>
        <table class="table w-full text-center">
            <thead class="bg-[#181818] sticky top-[3.7rem] z-10">
                <tr>
                    <For each={Fields}>
                        {field => <th>
                            <Switch fallback={ComUtils.tr(field)}>
                                <Match when={field === 'size'}>
                                    <button class="w-full flex gap-1 justify-center items-center" onclick={() => sortList(field)}>
                                        <span>
                                            {ComUtils.tr(field)}
                                        </span>
                                        <Show when={sort().key === field && sort().order > -1}>
                                            <img class={`size-3 ${sort().order == 1 ? 'rotate-180' : ''}`} src={sortIcon} alt="" srcset="" />
                                        </Show>
                                    </button>
                                </Match>
                                <Match when={field === 'installTime'}>
                                    <button class="w-full flex gap-1 justify-center items-center" onclick={() => sortList(field)}>
                                        <span>
                                            {ComUtils.tr(field)}
                                        </span>
                                        <Show when={sort().key === field && sort().order > -1}>
                                            <img class={`size-3 ${sort().order == 1 ? 'rotate-180' : ''}`} src={sortIcon} alt="" srcset="" />
                                        </Show>
                                    </button>
                                </Match>
                                <Match when={field === 'updateTime'}>
                                    <button class="w-full flex gap-1 justify-center items-center" onclick={() => sortList(field)}>
                                        <span>
                                            {ComUtils.tr(field)}
                                        </span>
                                        <Show when={sort().key === field && sort().order > -1}>
                                            <img class={`size-3 ${sort().order == 1 ? 'rotate-180' : ''}`} src={sortIcon} alt="" srcset="" />
                                        </Show>
                                    </button>
                                </Match>
                            </Switch>
                        </th>}
                    </For>
                </tr>
            </thead>
            <tbody class="text-[#d3d3d3]">
                <For each={projects()}>
                    {
                        item => <tr class="relative">
                            <For each={Fields.slice(0, Fields.length - 1)}>
                                {key => <td class="py-2">
                                    <Switch fallback={getValue(item, key)}>
                                        <Match when={key == 'name'}>
                                            <p class=" inline-block whitespace-nowrap max-w-48 overflow-hidden text-ellipsis" title={getValue(item, key)}>
                                                {getValue(item, key)}
                                            </p>
                                        </Match>
                                        <Match when={key == 'author'}>
                                            <p class=" inline-block whitespace-nowrap max-w-48 overflow-hidden text-ellipsis" title={getValue(item, key)}>
                                                {getValue(item, key)}
                                            </p>
                                        </Match>
                                        <Match when={key == 'installTime'}>
                                            <span class="text-xs">
                                                {ComUtils.formatDate(getValue(item, key), false)}
                                            </span>
                                        </Match>
                                        <Match when={key == 'updateTime'}>
                                            <span class="text-xs">
                                                {ComUtils.formatDate(getValue(item, key), false)}
                                            </span>
                                        </Match>
                                        <Match when={key == 'size'}>
                                            {ComUtils.formatBytes(getValue(item, key))}
                                        </Match>
                                        <Match when={key == 'version'}>
                                            <p class=" inline-block whitespace-nowrap max-w-48 overflow-hidden text-ellipsis" title={getValue(item, key)}>
                                                {getValue(item, key)}
                                            </p>
                                        </Match>
                                        <Match when={key == 'type'}>
                                            {ComUtils.tr('project_type_' + (getValue(item, key) || 'content'))}
                                        </Match>
                                        <Match when={key == 'error'}>
                                            <p class=" text-center" title={getValue(item, key)}>
                                                <Show when={getValue(item, key)} fallback="-">
                                                    <img class="size-5 inline-block cursor-help" src={errorIcon} alt="err" onclick={() => copyErr(item.error)} />
                                                </Show>
                                            </p>
                                        </Match>
                                        <Match when={key == 'programmingType'}>
                                            {ComUtils.tr('programming_type_' + (getValue(item, key) || 'blockly'))}
                                        </Match>
                                        <Match when={key == 'enabled'}>
                                            <p class=" text-center">
                                                <Show when={!getValue(item, 'type') || getValue(item, 'type') === 'content' || getValue(item, 'type') === 'editorPlugin'} fallback={<span>-</span>}>
                                                    <MyButton loading={() => itemLoading().loading && itemLoading().id === item.id} onclick={() => toggleEnabled(item)}>
                                                        <img class="size-6 inline-block" src={getEnabledIcon(item)} alt="enabled" />
                                                    </MyButton>
                                                </Show>
                                            </p>
                                        </Match>
                                    </Switch>

                                </td>}
                            </For>
                            <td>
                                <div class="opreation bg-[#26292e] py-3 absolute right-0 top-0 flex gap-3 justify-center min-w-[12rem]">
                                    <button title={ComUtils.tr('delete')} onclick={() => showDelete(item)}>
                                        <img class="w-5 h-5" src={delIcon} alt="delete" />
                                    </button>
                                    <button title={ComUtils.tr('edit')} onclick={() => editPopup(item)}>
                                        <img class="w-5 h-5" src={editIcon} alt="editIcon" />
                                    </button>
                                    <Show when={item.useDog}>
                                        <button title={ComUtils.tr('template')} onclick={() => showHtml(item)}>
                                            <img class="w-5 h-5" src={htmlIcon} alt="htmlIcon" />
                                        </button>
                                    </Show>
                                    <button title={ComUtils.tr('code')} onclick={() => goEditor(item)}>
                                        <img class="w-5 h-5" src={codeIcon} alt="codeIcon" />
                                    </button>
                                    <Show when={item.type && (item.type === 'window' || item.type === 'sidePanel')}>
                                        <button title={ComUtils.tr('run')} onclick={() => runScript(item)}>
                                            <img class="w-5 h-5" src={runIcon} alt="run" />
                                        </button>
                                    </Show>
                                    <button title={ComUtils.tr('export')} onclick={() => downloadItem(item)}>
                                        <img class="w-5 h-5" src={downloadIcon} alt="downloadIcon" />
                                    </button>
                                </div>
                            </td>
                        </tr>
                    }
                </For>
            </tbody>
        </table>
        <Show when={projects().length === 0}>
            <div class=" text-center mt-8 text-x">
                <button class="inline-block text-[#497ded] font-bold" onclick={newPopup}>
                    {ComUtils.tr('create_project_tips')}
                </button>
            </div>
        </Show>
        <Popup title={getEditPopupTitle()} show={popup} close={() => closePopup(true)} ok={saveData}>
            <div class="flex flex-col gap-2">
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('name')}
                    </p>
                    <input class="w-full" type="text" value={form().name} onchange={(e) => setFormValue('name', e.target.value)} />
                </div>
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('programming_type')}
                    </p>
                    <select class="w-full" value={form().programmingType} onchange={(e) => setFormValue('programmingType', e.target.value as any)}>
                        <For each={programmingTypes}>
                            {
                                val => <option value={val}>
                                    {ComUtils.tr('programming_type_' + val)}
                                </option>
                            }
                        </For>
                    </select>
                </div>
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('project_type')}
                    </p>
                    <select class="w-full" value={form().type} onchange={(e) => setFormValue('type', e.target.value as any)}>
                        <For each={ProjectTypes}>
                            {
                                val => <option value={val}>
                                    {ComUtils.tr('project_type_' + val)}
                                </option>
                            }
                        </For>
                    </select>
                </div>
                <Show when={form().type === 'window'}>
                    <details>
                        <summary class="text-[#999] select-none cursor-pointer">
                            {ComUtils.tr('project_window')}
                        </summary>
                        <div class="flex flex-col gap-3">
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('project_window_icon')}
                                </p>
                                <input class="w-full" type="text" value={windowInfo().icon || ''} onchange={(e) => setWindowFormValue('icon', e.target.value)} />
                            </div>
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('script_window_left')}
                                </p>
                                <input class="w-full" type="number" value={windowInfo().left || ''} onchange={(e) => setWindowFormValue('left', e.target.value)} />
                            </div>
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('script_window_top')}
                                </p>
                                <input class="w-full" type="number" value={windowInfo().top || ''} onchange={(e) => setWindowFormValue('top', e.target.value)} />
                            </div>
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('script_window_width')}
                                </p>
                                <input class="w-full" type="number" value={windowInfo().width || ''} onchange={(e) => setWindowFormValue('width', e.target.value)} />
                            </div>
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('script_window_height')}
                                </p>
                                <input class="w-full" type="number" value={windowInfo().height || ''} onchange={(e) => setWindowFormValue('height', e.target.value)} />
                            </div>
                        </div>
                    </details>
                </Show>
                <Show when={form().type === 'content'}>
                    <details>
                        <summary class="text-[#999] select-none cursor-pointer">
                            {ComUtils.tr('project_type_content')}
                        </summary>
                        <div class="flex flex-col gap-3">
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('matches')}
                                </p>
                                <textarea class="w-full" rows={3} value={form().matches.join('\n')} onchange={(e) => setFormValue('matches', e.target.value.split('\n'))} placeholder={'*://*.xxx.com/* ' + ComUtils.tr('form_list_placeholder')} />
                            </div>
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('url_exclude')}
                                </p>
                                <textarea class="w-full" rows={3} value={form().exclude?.join('\n') || ''} onchange={(e) => setFormValue('exclude', e.target.value.split('\n'))} placeholder={'*://*.xxx.com/* ' + ComUtils.tr('form_list_placeholder')} />
                            </div>
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('url_include')}
                                </p>
                                <textarea class="w-full" rows={3} value={form().include?.join('\n') || ''} onchange={(e) => setFormValue('include', e.target.value.split('\n'))} placeholder={'*://*.xxx.com/* ' + ComUtils.tr('form_list_placeholder')} />
                            </div>
                            <div>
                                <p class="text-[#999]">
                                    {ComUtils.tr('runAt')}
                                </p>
                                <select class="w-full" value={form().runAt} onchange={(e) => setFormValue('runAt', e.target.value as any)}>
                                    <For each={RunAts}>
                                        {
                                            val => <option value={val}>
                                                {ComUtils.tr(val)}
                                            </option>
                                        }
                                    </For>
                                </select>
                            </div>
                        </div>
                    </details>
                </Show>
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('project_description')}
                    </p>
                    <textarea class="w-full" rows={2} value={form().description || '-'} onchange={(e) => setFormValue('description', e.target.value)} />
                </div>
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('lib_requires')}
                    </p>
                    <textarea class="w-full" rows={3} value={form().requires?.join('\n') || ''} onchange={(e) => setFormValue('requires', e.target.value.split('\n'))} placeholder={'https://cdn.xx.com/a.js ' + ComUtils.tr('form_list_placeholder')} />
                </div>
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('reference_resources')}
                    </p>
                    <textarea class="w-full" rows={3} value={form().resources?.join('\n') || ''} onchange={(e) => setFormValue('resources', e.target.value.split('\n'))} placeholder={'img_a https://cdn.xx.com/a.png ' + ComUtils.tr('form_list_placeholder')} />
                </div>
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('author')}
                    </p>
                    <input class="w-full" type="text" value={form().author} onchange={(e) => setFormValue('author', e.target.value)} />
                </div>
                <div>
                    <p class="text-[#999]">
                        {ComUtils.tr('version')}
                    </p>
                    <input class="w-full" type="text" value={form().version} onchange={(e) => setFormValue('version', e.target.value)} />
                </div>
                <Show when={form().type === 'content' || form().type === 'editorPlugin'}>
                    <label class="text-[#999] align-middle">
                        <input type="checkbox" checked={form().enabled} onchange={(e) => setFormValue('enabled', e.target.checked)} />
                        <span class=" ml-1">
                            {ComUtils.tr('enabled')}
                        </span>
                    </label>
                </Show>
                <Show when={form().type !== 'editorPlugin'}>
                    <label class="text-[#999] align-middle">
                        <input type="checkbox" checked={form().useDog} onchange={(e) => setFormValue('useDog', e.target.checked)} />
                        <span class=" ml-1">
                            {ComUtils.tr('use_dog')}
                        </span>
                    </label>
                </Show>
            </div>
        </Popup>
        <Popup show={deletePopup} title={ComUtils.tr('warning')} close={() => setDeletePopup(false)} ok={deleteData}>
            <h3>{ComUtils.tr('delete_warn_msg')}</h3>
        </Popup>
        <Templat show={templatPopup} data={form} save={saveTemplate} close={() => setTemplatPopup(false)} />

    </div>
}